var table, params, $, columns;
layui.use(['jquery', 'form', 'laydate', 'formSelects','upload'], function () {
    $ = jQuery = layui.$;
    var form = layui.form;
    var laydate = layui.laydate;
    var formSelects = layui.formSelects;
    var upload = layui.upload;

    $.ajax({
        type: "POST",
        url: ctx + '/sys_admin/mineservice/findById',
        data: {'id': id,"tablename":tablename},
        async: false,
        success: function (data) {
            columns=data
        }
    });
    $.ajax({
        type: "POST",
        url: ctx+'/sys_admin/mineservice/showColumns',
        data: {'moduleid': moduleid},
        async: false,
        success: function (data) {
            //columns = JSON.parse(item);
            $('#itemid').val(columns['id']);
            $.each(data, function (i, column) {
                var type = column.column_type;
                var nullable = column.is_nullable;
                if (type == 'select') {
                    if(nullable == "NO"){
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item">' +
                            '        <label class="layui-form-label">' + column.column_comment + '<font style="color: red">*</font></label>' +
                            '        <div class="layui-input-block">' +
                            '           <select name="' + column.column_name + '" xm-select="' + column.column_name + '" lay-verify="required"  xm-select-radio xm-select-search  >' +
                            '               <option value="">选择' + column.column_comment + '</option>' +
                            '           </select>' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }else{
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item">' +
                            '        <label class="layui-form-label">' + column.column_comment + '</label>' +
                            '        <div class="layui-input-block">' +
                            '           <select name="' + column.column_name + '" xm-select="' + column.column_name + '" lay-verify=""  xm-select-radio xm-select-search  >' +
                            '               <option value="">选择' + column.column_comment + '</option>' +
                            '           </select>' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }

                    formSelects.data(column.column_name, 'server', {
                        url: ctx+'/sys_admin/mineservice/getSelectData?foreignTable=' + column.foreignTable+'&foreignKey='+column.foreignKey,
                        success: function (id, url, searchVal, result) {
                            formSelects.value(column.column_name, [(columns[column.column_name]==undefined?"":columns[column.column_name])]);
                        }
                    });
                } else if (type == 'sex') {
                    var result = columns[column.column_name];
                    if(nullable == "NO"){
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item" pane="">' +
                            '        <label class="layui-form-label">' + column.column_comment + '<font style="color: red">*</font></label>' +
                            '        <div class="layui-input-block">' +
                            '           <input type="radio" name="' + column.column_name + '" value="1" title="男" ' + ((result == 1 || result == null) ? "checked=''" : "") + '>' +
                            '           <input type="radio" name="' + column.column_name + '" value="2" title="女" ' + (result == 2 ? "checked=''" : "") + '>' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }else{
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item" pane="">' +
                            '        <label class="layui-form-label">' + column.column_comment + '</label>' +
                            '        <div class="layui-input-block">' +
                            '           <input type="radio" name="' + column.column_name + '" value="1" title="男" ' + ((result == 1 || result == null) ? "checked=''" : "") + '>' +
                            '           <input type="radio" name="' + column.column_name + '" value="2" title="女" ' + (result == 2 ? "checked=''" : "") + '>' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }
                } else if (type == 'yesorno') {
                    var result = columns[column.column_name];
                    if(nullable == "NO") {
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item" pane="">' +
                            '        <label class="layui-form-label">' + column.column_comment + '<font style="color: red">*</font></label>' +
                            '        <div class="layui-input-block">' +
                            '           <input type="radio" name="' + column.column_name + '" value="1" title="是" ' + ((result == 1 || result == null) ? "checked=''" : "") + '>' +
                            '           <input type="radio" name="' + column.column_name + '" value="2" title="否" ' + (result == 2 ? "checked=''" : "") + '>' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }else{
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item" pane="">' +
                            '        <label class="layui-form-label">' + column.column_comment + '</label>' +
                            '        <div class="layui-input-block">' +
                            '           <input type="radio" name="' + column.column_name + '" value="1" title="是" ' + ((result == 1 || result == null) ? "checked=''" : "") + '>' +
                            '           <input type="radio" name="' + column.column_name + '" value="2" title="否" ' + (result == 2 ? "checked=''" : "") + '>' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }
                } else if (type == 'haveorno') {
                    var result = columns[column.column_name];
                    if(nullable == "NO") {
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item" pane="">' +
                            '        <label class="layui-form-label">' + column.column_comment + '<font style="color: red">*</font></label>' +
                            '        <div class="layui-input-block">' +
                            '           <input type="radio" name="' + column.column_name + '" value="1" title="有" ' + ((result == 1 || result == null) ? "checked=''" : "") + '>' +
                            '           <input type="radio" name="' + column.column_name + '" value="2" title="无" ' + (result == 2 ? "checked=''" : "") + '>' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }else{
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item" pane="">' +
                            '        <label class="layui-form-label">' + column.column_comment + '</label>' +
                            '        <div class="layui-input-block">' +
                            '           <input type="radio" name="' + column.column_name + '" value="1" title="有" ' + ((result == 1 || result == null) ? "checked=''" : "") + '>' +
                            '           <input type="radio" name="' + column.column_name + '" value="2" title="无" ' + (result == 2 ? "checked=''" : "") + '>' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }
                } else if (type == 'text' || type == 'longtext') {
                    if(nullable == "NO") {
                        $('#serviceForm').append('' +
                            '<div class="layui-row">' +
                            '    <div class="layui-col-xs12">' +
                            '        <div class="layui-form-item layui-form-text">' +
                            '            <label class="layui-form-label">' + column.column_comment + '<font style="color: red">*</font></label>' +
                            '            <div class="layui-input-block">' +
                            '                <textarea name="' + column.column_name + '" placeholder="请输入' + column.column_comment + '" class="layui-textarea">' + (columns[column.column_name] == undefined ? "" : columns[column.column_name]) + '</textarea>' +
                            '            </div>' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }else{
                        $('#serviceForm').append('' +
                            '<div class="layui-row">' +
                            '    <div class="layui-col-xs12">' +
                            '        <div class="layui-form-item layui-form-text">' +
                            '            <label class="layui-form-label">' + column.column_comment + '</label>' +
                            '            <div class="layui-input-block">' +
                            '                <textarea name="' + column.column_name + '" placeholder="请输入' + column.column_comment + '" class="layui-textarea">' + (columns[column.column_name] == undefined ? "" : columns[column.column_name]) + '</textarea>' +
                            '            </div>' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }
                } else if (type == 'varchar') {
                    if(nullable == "NO") {
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item">' +
                            '        <label class="layui-form-label">' + column.column_comment + '<font style="color: red">*</font></label>' +
                            '        <div class="layui-input-block">' +
                            '           <input type="text" name="' + column.column_name + '" id="' + column.column_name + 'id" lay-verify="required" placeholder="请输入' + column.column_comment + '" autocomplete="off" class="layui-input" value="' + ((columns[column.column_name] == undefined ? "" : columns[column.column_name]) == undefined ? "" : (columns[column.column_name] == undefined ? "" : columns[column.column_name])) + '">' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }else{
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item">' +
                            '        <label class="layui-form-label">' + column.column_comment + '</label>' +
                            '        <div class="layui-input-block">' +
                            '           <input type="text" name="' + column.column_name + '" id="' + column.column_name + 'id" lay-verify="" placeholder="请输入' + column.column_comment + '" autocomplete="off" class="layui-input" value="' + ((columns[column.column_name] == undefined ? "" : columns[column.column_name]) == undefined ? "" : (columns[column.column_name] == undefined ? "" : columns[column.column_name])) + '">' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }
                } else if (type == 'date') {
                    var result = columns[column.column_name]==undefined?"":columns[column.column_name].substring(0, 10);
                    if(nullable == "NO") {
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item">' +
                            '        <label class="layui-form-label">' + column.column_comment + '<font style="color: red">*</font></label>' +
                            '        <div class="layui-input-block">' +
                            '           <input id="' + column.column_name + 'id" name="' + column.column_name + '" lay-verify="required" placeholder="请输入' + column.column_comment + '" autocomplete="off" class="layui-input" value="' + result + '">' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }else{
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item">' +
                            '        <label class="layui-form-label">' + column.column_comment + '</label>' +
                            '        <div class="layui-input-block">' +
                            '           <input id="' + column.column_name + 'id" name="' + column.column_name + '" lay-verify="" placeholder="请输入' + column.column_comment + '" autocomplete="off" class="layui-input" value="' + result + '">' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }
                    laydate.render({
                        elem: '#' + column.column_name + 'id',
                        trigger: 'click'
                    });
                } else if (type == 'datetime') {
                    var result = columns[column.column_name]==undefined?"":columns[column.column_name].substring(0, 19);
                    if(nullable == "NO") {
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item">' +
                            '        <label class="layui-form-label">' + column.column_comment + '<font style="color: red">*</font></label>' +
                            '        <div class="layui-input-block">' +
                            '           <input id="' + column.column_name + 'id" name="' + column.column_name + '" lay-verify="required" placeholder="请输入' + column.column_comment + '" autocomplete="off" class="layui-input" value="' + result + '">' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }else{
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item">' +
                            '        <label class="layui-form-label">' + column.column_comment + '</label>' +
                            '        <div class="layui-input-block">' +
                            '           <input id="' + column.column_name + 'id" name="' + column.column_name + '" lay-verify="" placeholder="请输入' + column.column_comment + '" autocomplete="off" class="layui-input" value="' + result + '">' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }
                    laydate.render({
                        elem: '#' + column.column_name + 'id',
                        type: 'datetime',
                        trigger: 'click'
                    });
                }else if (type == 'file') {
                    if(menutype==1){
                        if(columns[column.column_name]==null||columns[column.column_name]==""){
                                $('#serviceForm').append('' +
                                ' <div class="layui-col-xs4">' +
                                '   <div class="layui-form-item">' +
                                '       <label class="layui-form-label">' + column.column_comment + '<font style="color: red">*</font></label>' +
                                '       <div class="layui-input-block">' +
                                '           <input type="text"  readonly="readonly" id="' + column.column_name +'" lay-data="{fileid:\'' + column.column_name +'\'}"  placeholder="请上传' + column.column_comment + '" autocomplete="off" class="layui-input" value="'+((columns[column.column_name]==undefined?"":columns[column.column_name].split("@")[0])==undefined?"":(columns[column.column_name]==undefined?"":columns[column.column_name].split("@")[0]))+'">' +
                                '            <input type="hidden" name="' + column.column_name + '" readonly="readonly" id="' + column.column_name +'id"   autocomplete="off" class="layui-input" value="'+((columns[column.column_name]==undefined?"":columns[column.column_name].split("@")[1])==undefined?"":(columns[column.column_name]==undefined?"":columns[column.column_name].split("@")[1]))+'">' +
                                '       </div>' +
                                '   </div>' +
                                ' </div>' +
                                ' <div class="layui-col-xs2">' +
                                '           <button id="reset-btn" type="reset" class="layui-btn layui-btn-primary">下载</button>' +
                                '           <button id="reset-btn" type="reset" class="layui-btn layui-btn-primary">预览</button>' +
                                ' </div>');
                        }else{
                            $('#serviceForm').append('' +
                                ' <div class="layui-col-xs4">' +
                                '   <div class="layui-form-item">' +
                                '       <label class="layui-form-label">' + column.column_comment + '<font style="color: red">*</font></label>' +
                                '       <div class="layui-input-block">' +
                                '           <input type="text"  readonly="readonly" id="' + column.column_name +'" lay-data="{fileid:\'' + column.column_name +'\'}"  placeholder="请上传' + column.column_comment + '" autocomplete="off" class="layui-input" value="'+((columns[column.column_name]==undefined?"":columns[column.column_name].split("@")[0])==undefined?"":(columns[column.column_name]==undefined?"":columns[column.column_name].split("@")[0]))+'">' +
                                '            <input type="hidden" name="' + column.column_name + '" readonly="readonly" id="' + column.column_name +'id"   autocomplete="off" class="layui-input" value="'+((columns[column.column_name]==undefined?"":columns[column.column_name].split("@")[1])==undefined?"":(columns[column.column_name]==undefined?"":columns[column.column_name].split("@")[1]))+'">' +
                                '       </div>' +
                                '   </div>' +
                                ' </div>' +
                                ' <div class="layui-col-xs2">' +
                                '           <button id="reset-btn" type="reset" onclick="downloadFile(\'' +columns[column.column_name].split("@")[0]+'\',\'' +columns[column.column_name].split("@")[1]+'\' )" class="layui-btn layui-btn-primary">下载</button>' +
                                '           <button id="reset-btn" type="reset" onclick="preview(\'' +columns[column.column_name].split("@")[1]+'\' )" class="layui-btn layui-btn-primary">预览</button>' +
                                ' </div>');
                        }
                    }else{
                        $('#serviceForm').append('' +
                            ' <div class="layui-col-xs6">' +
                            '   <div class="layui-form-item">' +
                            '       <label class="layui-form-label">' + column.column_comment + '<font style="color: red">*</font></label>' +
                            '       <div class="layui-input-block layui-upload">' +
                            '           <input type="text"  readonly="readonly" id="' + column.column_name +'" lay-data="{fileid:\'' + column.column_name +'\'}"  placeholder="请上传' + column.column_comment + '" autocomplete="off" class="layui-input fileupload" value="'+((columns[column.column_name]==undefined?"":columns[column.column_name].split("@")[0])==undefined?"":(columns[column.column_name]==undefined?"":columns[column.column_name].split("@")[0]))+'">' +
                            /*'           <input type="hidden" name="' + column.column_name + '" readonly="readonly" id="' + column.column_name +'id"   autocomplete="off" class="layui-input" value="'+((columns[column.column_name]==undefined?"":columns[column.column_name].split("@")[1])==undefined?"":(columns[column.column_name]==undefined?"":columns[column.column_name].split("@")[1]))+'">' +*/
                            '           <input type="hidden" name="' + column.column_name + '" readonly="readonly" id="' + column.column_name +'id"   autocomplete="off" class="layui-input" value="'+((columns[column.column_name]==undefined?"":columns[column.column_name]))+'">' +
                            '       </div>' +
                            '   </div>' +
                            ' </div>');
                    }
                }  else {
                    if(nullable == "NO") {
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item">' +
                            '        <label class="layui-form-label">' + column.column_comment + '<font style="color: red">*</font></label>' +
                            '        <div class="layui-input-block">' +
                            '           <input type="number" name="' + column.column_name + '" id="' + column.column_name + 'id"  lay-verify="required|number" placeholder="请输入' + column.column_comment + '" autocomplete="off" class="layui-input" value="' + (columns[column.column_name] == undefined ? "" : columns[column.column_name]) + '">' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }else{
                        $('#serviceForm').append('' +
                            '<div class="layui-col-xs6">' +
                            '    <div class="layui-form-item">' +
                            '        <label class="layui-form-label">' + column.column_comment + '</label>' +
                            '        <div class="layui-input-block">' +
                            '           <input type="number" name="' + column.column_name + '" id="' + column.column_name + 'id" lay-verify="" placeholder="请输入' + column.column_comment + '" autocomplete="off" class="layui-input" value="' + (columns[column.column_name] == undefined ? "" : columns[column.column_name]) + '">' +
                            '        </div>' +
                            '    </div>' +
                            '</div>');
                    }
                }
            });
            form.render();
            $.ajax({
                type: "POST",
                url: ctx+'/sys_admin/calculate/getCalList',
                data: {'moduleid': moduleid},
                async: false,
                success: function (cals) {
                    $.each(cals, function (i, cal) {
                        var destcolumn = cal.column_name;
                        $(':input[name="'+destcolumn+'"]').attr('readonly','readonly');
                        var calstr = cal.calculate;
                        var map = getMap(calstr);
                        var keyArray = Object.keys(map);
                        if (keyArray.length > 0) {
                            $.each(keyArray, function (i, key) {
                                $(':input[name="'+key+'"]').bind("blur", function () {
                                    var value = $(':input[name="'+key+'"]').val();
                                    map[key] = value == ""?0:value;
                                    var mapstr = JSON.stringify(map);
                                    getCalculateValue(destcolumn, mapstr, calstr);
                                });
                            });
                            //以下方法不推荐
                            /*$(".layui-input").each(function() {
                                $(this).bind("blur",function(){
                                    if (calstr.indexOf(this.name) > -1) {
                                        map[this.name] = this.value;
                                        var mapstr = JSON.stringify(map);
                                        console.log(mapstr);
                                        getCalculateValue(mapstr, calstr);
                                    }
                                })
                            });*/
                        }
                    })
                }
            });
        }
    });

    var uploadInst = upload.render({
        elem: '.fileupload'
        ,url: ctx+'/sys_admin/mineservice/uploadfile?tablename='+tablename //上传接口
        ,accept: 'file'//允许上传的文件类型
        ,before: function(obj){
            //alert(this.fileid);
        }
        ,done: function(res){
            //上传成功
            if(res.success == 1){
                var fileid = this.fileid;
                $('#'+fileid).val(res.name);
                // $('#'+fileid+'id').val('{"name":"'+res.name+'","url":"'+res.url+'"}');
                $('#'+fileid+'id').val(res.name+'@'+res.url);
            }
        }
        ,error: function(){
            uploadInst.upload();
        }
    });
    form.on('submit', function (data) {
        $.post(ctx+'/sys_admin/mineservice/save', data.field, function (result) {
            if (result.success) {
                table.reload({
                    method : 'post',
                    where: params.field,
                    page: {
                        curr: params.curr
                    }
                });
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            } else {
                layer.msg(result.msg);
            }
        }, 'json');
        return false;
    });

});
function downloadFile(name,url) {
    downFileByIframe(ctx+"/sys_admin/mineservice/tableFileDownload?name="+name+"&url="+url);
}
function preview(path) {
    var fileUrl = ctx+path;
    var url = "http://116.63.43.8:8012/onlinePreview?url=" + encodeURIComponent(fileUrl);
    var winHeight = window.document.documentElement.clientHeight-10;
    window.open(url,"_blank", "height=" + winHeight + ", top=30, left=40, toolbar=no, menubar=no, scrollbars=yes, resizable=yes ");
}

function getMap(calstr) {
    var map = {};
    $(".layui-input").each(function() {
        if (calstr.indexOf(this.name) > -1) {
            map[this.name] = 0;
        }
    });
    return map;
}

function getCalculateValue(destcolumn, mapstr, calstr) {
    $.ajax({
        type: "POST",
        url: ctx + '/sys_admin/calculate/calculate',
        data: {'formula': calstr, 'mapstr':mapstr},
        //async: false,
        success: function (data) {
            $(':input[name="'+destcolumn+'"]').val(data);
        }
    });
}

//接口获取参数
function interfaceBtn(){
    $.post(ctx +'/sys_admin/interface/sendRequest', $("form").serialize(), function(result) {
        if (result.success) {
            var data = result.data;
            for (var i = 0; i < data.length; i++) {
                var info = data[i];
                $("#"+info.name+"id").val(info.value)
            }
        }else {
            layer.msg(result.msg);
        }
    }, 'json');
}